package com.korovyansk.mapsproto.api;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.os.Environment;

import com.korovyansk.mapsproto.application.MapsProtoApplication.PerformanceTimer;
import com.korovyansk.mapsproto.beans.Position;
import com.korovyansk.mapsproto.beans.Tile;
import com.korovyansk.mapsproto.utils.IOUtils;

/**
 * Utility class for access to tiles cache
 * 
 * @author korovyansk
 */
public class TilesCache {

	public static Tile NO_TILE = new Tile(null, new Position(-1, -1));

	public TilesCache(Context context) {
		final String pathToExternalStorage = Environment.getExternalStorageDirectory().getAbsolutePath();
		final String pathToCacheDir = String.format("Android/data/%s/cache", context.getPackageName());
		cacheDirPath = IOUtils.join(pathToExternalStorage, pathToCacheDir);
	}

	/**
	 * loads Tile from cache in external storage
	 * 
	 * @param context
	 * @param x
	 * @param y
	 * @return Tile from cache if it exists, else Tile equals NO_TILE
	 */
	public Tile loadTile(final Position position) {
		PerformanceTimer timer = new PerformanceTimer("loadTile", true);
		final File tileFile = new File(pathToTile(position));
		if (!tileFile.exists()) {
			timer.check();
			return NO_TILE;
		}
		final Bitmap bitmap = BitmapFactory.decodeFile(tileFile.getAbsolutePath());
		return (bitmap == null ? NO_TILE : new Tile(bitmap, position));
	}

	/**
	 * saves Tile to cache in external storage
	 * 
	 * @param context
	 * @param tile
	 * @throws FileNotFoundException
	 */
	public void saveTile(final Tile tile) throws FileNotFoundException {
		final File tileFile = new File(pathToTile(tile.position));
		IOUtils.makeDirs(tileFile);
		final FileOutputStream tileOutput = new FileOutputStream(tileFile);
		tile.bitmap.compress(CompressFormat.PNG, 0, tileOutput);
	}

	/**
	 * clears cache
	 * @return true if cache was successfully cleared
	 */
	public boolean clearCache() {
		final File cacheDir = new File(cacheDirPath);
		return IOUtils.clearDir(cacheDir);
	}

	protected String pathToTile(final Position position) {
		final String tileName = String.format("%d_%d.png", position.x, position.y);
		return IOUtils.join(cacheDirPath, tileName);
	}

	private String cacheDirPath;
}
